// 轮播管理子组件 编辑与添加共用弹框
import React, { useState, useEffect } from 'react';
import { Button, Upload, Modal, message, Form, Input, Switch, Select, DatePicker, InputNumber } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { RcFile } from 'antd/es/upload/interface';
import '../../../css/AddorRev.css'
import dayjs from 'dayjs'
import { addSlide, revSlide, upProtoSlide } from '../../../../api/opreationApi'
import getSelectTime from '../../../../utils/date'

// 表格接口
interface DataType {
  key: React.Key;
  carouselTital: string;//名字
  carouselId: number;//序号
  carouselTimePar: string;//上架时间段
  carouselLocation: number;//位置
  carouselType: string;//类型
  carouselPic: string;//图片
  carouselTime: string;//上架时间
  carouselIuptimeEnd: string;
  carouselUptimeStart: string;
  carouselUpordown: number;//是否上架
}

// 参数接口
interface PropsType {
  modalClose(): void
  isModalOpen: boolean
  head: string | null
  nowRev: DataType | null
  getData(): void
}


export default function AddorRev(props: PropsType) {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string | null>();//装图片
  const [img, setImg] = useState<string>('')  //装选中图片的file 类型
  const [form] = Form.useForm()//使用From表单，用于默认值
  const [imgFile, setImgFile] = useState(null)  //存放选中图片的file属性
  // 初始化
  useEffect(() => {
    if (props.head === '添加') {
      setImageUrl(null)
      setImg('')
      form.setFieldsValue({
        carouselTime: null,
        timeQuantum: null,
        carouselTital: null,
        carouselLocation: null,
        carouselType: null,
        carouselUpordown: null
      })
    } else {
      setImageUrl(`http://dsq.ljc.icu:8080` + props.nowRev?.carouselPic)
      setImg('')
      form.setFieldsValue({
        carouselTital: props.nowRev?.carouselTital,
        carouselLocation: props.nowRev?.carouselLocation,
        carouselTime: dayjs(props.nowRev?.carouselTime),
        carouselType: props.nowRev?.carouselType,
        carouselUpordown: props.nowRev?.carouselUpordown,
        timeQuantum: [dayjs(props.nowRev?.carouselUptimeStart), dayjs(props.nowRev?.carouselIuptimeEnd)]
      })
    }
  }, [props])

  // 对话框部分
  const handleOk = () => {
    props.modalClose()
  };

  const handleCancel = () => {
    props.modalClose()
  };
  // 表单部分
  const onFinish = (values: any) => {
    const data = {
      "carouselUptimeStart": getSelectTime(values.timeQuantum[0]),
      "carouselIuptimeEnd": getSelectTime(values.timeQuantum[1]),
      "carouselType": values.carouselType,
      "carouselUpordown": values.carouselUpordown ? 1 : 0,
      "carouselLocation": values.carouselLocation,
      "carouselTital": values.carouselTital,
      "carouselTime": getSelectTime(values.carouselTime),
      "carouselPic": img
    }
    if (props.head === '添加') {
      addSlide(data).then(res => {
        props.getData()
        message.success('添加成功！')
      })
    } else {
      revSlide({ ...data, carouselId: props.nowRev?.carouselId }).then(res => {
        props.getData()
        message.success('修改成功！')
      })
    }
    props.modalClose()
  };

  // 时间段选择
  const { RangePicker } = DatePicker;
  /* 和图片相关的函数 */
  // 上传图片
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  //文件被改变的时候执行的回调
  const handleChange = async (info: any) => {
    let { file } = info
    //准备装数据的盒子
    let formData = new FormData()
    formData.append('file', file)

    // 发起请求
    upProtoSlide(formData).then(res => {
      setImageUrl(`http://dsq.ljc.icu:8080` + res.data)
      setImg(res.data)
    })


    // 判断上传的文件类型为不为图片类型
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
    if (!isJpgOrPng) {
      return message.error('你应该上传图片类型');
    }
    //判断文件大小  是否小于2M
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      return message.error('图片太大了，请上传小于2M 的文件');
    }

    //让图片显示出来
    getBase64(info.file, (url) => {
      //当文件转完过后就会执行
      setImageUrl(url)
    });
  };
  const beforeUpload = () => {
    return false
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  return (
    <>
      <Modal title={props.head} open={props.isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
          form={form}
        >
          {/* 标题 */}
          <Form.Item
            label="轮播标题"
            name="carouselTital"
            rules={[{ required: true, message: '请输入轮播标题！' }]}
            initialValue={props.nowRev?.carouselTital}
          >
            <Input placeholder="请输入轮播标题！" />
          </Form.Item>
          {/* 位置 */}
          <Form.Item
            label="位置"
            name="carouselLocation"
            rules={[{ required: true, message: '请输入位置！' }]}
            initialValue={props.nowRev?.carouselLocation}
          >
            <InputNumber placeholder="请输入位置！" />
          </Form.Item>
          {/* 图片 */}
          <Form.Item
            label="封面图片"
            name="carouselPic"
            valuePropName="fileList"  /* 子节点的值的属性 */
            getValueFromEvent={e => { /* 设置如何将 event 的值转换成字段值 */
              if (Array.isArray(e)) {
                return e
              }
              return e && e.fileList
            }}
          >
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ?
                <img
                  src={imageUrl}
                  alt="avatar"
                  width={50}
                  height={50} />
                : uploadButton}
            </Upload>
          </Form.Item>
          {/* 类型 */}
          <Form.Item
            label='类型：'
            name='carouselType'
            rules={[{ required: true, message: '请选择类型！' }]}
            initialValue={props.nowRev?.carouselType}
          >
            <Select
              style={{ width: 120 }}
              allowClear
              options={[{ value: 'H5', label: 'H5' }, { value: '商品', label: '商品' }, { value: '专区', label: '专区' }]}
              className='drop'
              placeholder="请选择状态"
            />
          </Form.Item>
          {/* 上架时间段 */}
          <Form.Item
            name='timeQuantum'
            label="上架时间段"
            initialValue={props.nowRev?.carouselUptimeStart}
          >
            <RangePicker showTime />
          </Form.Item>
          {/* 预设上架时间 */}
          <Form.Item
            name='carouselTime'
            label="预设上架时间"
            labelAlign='right'
            initialValue={props.nowRev?.carouselTime}
          >
            <DatePicker showTime />
          </Form.Item>
          {/* 是否上架开关 */}
          <Form.Item
            name='carouselUpordown'
            label="上架"
            valuePropName='checked'
            initialValue={props.nowRev?.carouselUpordown}>
            <Switch />
          </Form.Item>
          {/* 操作按钮 */}
          <Form.Item wrapperCol={{ offset: 8, span: 16 }} className='opreate'>
            <Button type="primary" htmlType="submit" className='submit'>提交</Button>
            <Button type="primary" onClick={handleCancel} className='cancel'>取消</Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
